package org.tcx.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.ValidatorException;
import org.tcx.common.LogUtil;
import org.tcx.common.json.JsonUtil;
import org.tcx.web.ajax.Action;
import org.tcx.web.ajax.AjaxConfig;
import org.xml.sax.SAXException;

@SuppressWarnings("serial")
public class AjaxServlet extends HttpServlet{
	private static Log log = LogFactory.getLog(AjaxServlet.class);
	private AjaxConfig config ;
	@Override
	public void init() throws ServletException {
		log.debug("enter");
		super.init();
		config = new AjaxConfig();
		try {
			config.init();
		} catch (ParserConfigurationException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (SAXException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (IOException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (ClassNotFoundException e) {
			log.error("", e);
			throw new ServletException(e);
		}
		log.debug("leave");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.debug("enter" + LogUtil.arg("req, resp", req, resp));
		String prams = req.getParameter("params");
		log.debug(LogUtil.arg("prams", prams));
		JSON json = JSONSerializer.toJSON(prams);
		log.debug(LogUtil.arg("json", json));
		String path = req.getServletPath();
		log.debug(LogUtil.arg("path", path));
		Action action = config.getAction(path);
		Object result;
		try {
			result = action.invoke(json,req,resp);
		} catch (SecurityException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (IllegalArgumentException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (ClassNotFoundException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (NoSuchMethodException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (IllegalAccessException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (InvocationTargetException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (InstantiationException e) {
			log.error("", e);
			throw new ServletException(e);
		} catch (ValidatorException e) {
			log.error("", e);
			throw new ServletException(e);
		}
		log.debug(LogUtil.arg("result", result));
		resp.setCharacterEncoding("UTF-8");
		JsonUtil.toJsonStr(result, resp.getWriter());
		log.debug("leave");
	}
}
